import axios from 'axios';

const API_URL = '/api/UniversalDoc';

export interface ConfigItem {
  id: string;
  name: string;
  icon: string;
  description?: string;
  content: string;
  htmlContent?: string;
  compiledContent?: string;
  createdDate: Date | string;
  updatedDate?: Date | string;
  agent_ids?: string[]; // 关联的智能体工具ID列表
  params?: Record<string, any>; // 单独保存的参数
  type?: 'quickTools' | 'MCPTools' | 'workflowComponents'; // 文档类型
}

export interface AgentTool {
  id: string;
  name: string;
  description: string;
  icon?: string;
  method?: string;
}

export interface ToolCategory {
  quickTools: AgentTool[];
  MCPTools: AgentTool[];
  workflowComponents: AgentTool[];
}

export const universalDocService = {
  /**
   * 获取所有配置文档列表
   */
  async getConfigList(type?: 'quickTools' | 'MCPTools' | 'workflowComponents'): Promise<ConfigItem[]> {
    try {
      const response = await axios.get(`${API_URL}/list`, {
        params: { type }
      });
      // 将字符串日期转换为Date对象
      return response.data.map((item: ConfigItem) => ({
        ...item,
        createdDate: new Date(item.createdDate),
        updatedDate: item.updatedDate ? new Date(item.updatedDate) : undefined
      }));
    } catch (error) {
      console.error('获取配置列表失败:', error);
      throw error;
    }
  },

  /**
   * 添加或更新配置文档
   */
  async saveConfig(config: ConfigItem): Promise<ConfigItem> {
    try {
      const response = await axios.post(`${API_URL}/add`, config);
      return {
        ...response.data,
        createdDate: new Date(response.data.createdDate),
        updatedDate: response.data.updatedDate ? new Date(response.data.updatedDate) : undefined
      };
    } catch (error) {
      console.error('保存配置失败:', error);
      throw error;
    }
  },

  /**
   * 删除配置文档
   */
  async deleteConfig(configId: string): Promise<void> {
    try {
      await axios.post(`${API_URL}/delete`, { config_id: configId });
    } catch (error) {
      console.error('删除配置失败:', error);
      throw error;
    }
  },

  /**
   * 从Common API 中获取所有工具列表
   */
  async getAgentTools(): Promise<ToolCategory> {
    try {
      const response = await axios.get('/api/common/tools/list');
      return response.data;
    } catch (error) {
      console.error('获取智能体工具列表失败:', error);
      throw error;
    }
  }
};

export default universalDocService; 